package site.leiwa._01_单例模式;


import site.leiwa.common.Unsafe;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;


@Unsafe("可以在方法方法签名前面加 synchronized 或内部加 synchronized")
public class _01Singleton {
    private static _01Singleton singleton = null;

    private _01Singleton() {
    }

    public static _01Singleton getInstance() {
        if (singleton == null) {
            singleton = new _01Singleton();
        }
        return singleton;
    }

    // 验证是否安全
    public static void main(String[] args) throws InterruptedException {
        ArrayList<String> list = new ArrayList<>(200);
        ArrayList<Thread> threads = new ArrayList<>(200);
        for (int i = 0; i < 100; i++) {
            Thread t = new Thread(() -> {
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                list.add(_01Singleton.getInstance().toString());
            });
            threads.add(t);
        }
        threads.forEach(Thread::start);
        Thread.sleep(2500);
        Set<String> set = new HashSet<>();
        boolean b = set.addAll(list);
        System.out.println(set.size());
    }
}